package com.tanhua.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.BlackList;
import com.tanhua.common.pojo.Settings;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.SettingsService;
import com.tanhua.common.utils.UserThreadLocal;

import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.service.*;
import com.tanhua.server.vo.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class MyCenterServiceImpl implements MyCenterService {

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private IMService imService;

    @Autowired
    private TanHuaService tanHuaService;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private BlackListService blackListService;

    /**
     * 根据userId查询用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //接收到的userId为null 表示使用当前的用户信息
            userId = UserThreadLocal.get().getId();
        }
        try {
            UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
            if (ObjectUtil.isNotEmpty(userInfo)) {
                UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
                userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
                userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
                return userInfoVo;
            }
        } catch (Exception e) {
            log.error("查询信息失败！！！ userId = " + userId);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改用户信息
     *
     * @param userInfoVo
     * @return
     */
    @Override
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        Date dateTime = DateUtil.parseDate(userInfoVo.getBirthday());

        int yearInit = DateUtil.year(dateTime);
        int yearNow = DateUtil.year(new Date());

        userInfo.setAge(yearNow - yearInit);

        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(), "K", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");

        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    /**
     * 查询喜欢，粉丝，互相喜欢的数量
     *
     * @return
     */
    @Override
    public CountsVo queryCounts() {
        User user = UserThreadLocal.get();

        Long loveCount = this.userLikeApi.queryLikeCount(user.getId());
        Long fanCount = this.userLikeApi.queryFanCount(user.getId());
        Long eachLoveCount = this.userLikeApi.queryMutualLikeCount(user.getId());
        return new CountsVo(eachLoveCount, loveCount, fanCount);
    }

    /**
     * 互相关注、我关注、粉丝、谁看过我 - 翻页列表
     *
     * @param type     1 互相关注 2 我关注 3 粉丝 4 谁看过我
     * @param page
     * @param pageSize
     * @param nickName
     * @return
     */
    @Override
    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickName) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        List<Object> userIdList = null;

        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (type) {
            case 1: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(user.getId(), page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 2: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(user.getId(), page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId");
                break;
            }
            case 3: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(user.getId(), page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 4: {
                PageInfo<Visitors> visitorsPageInfo = this.visitorsApi.topVisitor(user.getId(), page, pageSize);
                userIdList = CollUtil.getFieldValues(visitorsPageInfo.getRecords(), "visitorUserId");
                break;
            }
            default:
                return pageResult;

        }
        if (CollUtil.isEmpty(userIdList)) {
            return pageResult;
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);

        if (StrUtil.isNotEmpty(nickName)) {
            queryWrapper.like("nick_name", nickName);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<UserLikeListVo> userLikeListVoList = new ArrayList<>();
        UserLikeListVo userLikeListVo;
        for (UserInfo userInfo : userInfoList) {
            userLikeListVo = new UserLikeListVo();
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            userLikeListVo.setNickname(userInfo.getNickName());

            userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(user.getId(), userInfo.getUserId()));

            // 存储缘分值的时候：1-30 缘分值  30-1缘分值
            Double score = this.recommendUserService.queryScore(user.getId(), userInfo.getUserId());
            userLikeListVo.setMatchRate(Convert.toInt(score));
            userLikeListVoList.add(userLikeListVo);
        }
        pageResult.setItems(userLikeListVoList);

        return pageResult;
    }

    /**
     * 从关注列表中取消喜欢
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean disLike(Long userId) {
        User user = UserThreadLocal.get();

        this.userLikeApi.notLikeUser(user.getId(), userId);
        if (this.userLikeApi.isMutualLike(user.getId(), userId)) {
            this.imService.removeUser(user.getId(), userId);
        }
        return true;
    }

    /**
     * 喜欢粉丝列表中的粉丝
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean likeFans(Long userId) {
        Boolean flag = this.tanHuaService.likeUser(userId);
        return flag;
    }

    /**
     * 查看通用配置
     *
     * @return
     */
    @Override
    public SettingsVo querySettings() {
        User user = UserThreadLocal.get();

        SettingsVo settingsVo = new SettingsVo();

        //设置用户的基本信息
        settingsVo.setId(user.getId());
        settingsVo.setPhone(user.getMobile());

        Settings settings = this.settingsService.querySettings(user.getId());

        if (Optional.ofNullable(settings).isPresent()) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());

        }
        //查询陌生人的问题
        settingsVo.setStrangerQuestion(this.tanHuaService.queryQuestion(user.getId()));

        return settingsVo;
    }

    @Override
    public void saveQuestions(String content) {
        User user = UserThreadLocal.get();

        this.questionService.save(user.getId(), content);
    }

    /**
     * 查询黑名单列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult queryBlacklist(Integer page, Integer pageSize) {

        User user = UserThreadLocal.get();

        IPage<BlackList> blackListIPage = this.blackListService.queryBlackList(user.getId(), page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(Convert.toInt(blackListIPage.getPages()));
        pageResult.setCounts(Convert.toInt(blackListIPage.getTotal()));
        pageResult.setPagesize(pageSize);

        List<BlackList> blackLists = blackListIPage.getRecords();
        if (!Optional.ofNullable(blackLists).isPresent()) {
            return pageResult;
        }
        List<Object> idList = CollUtil.getFieldValues(blackLists, "blackUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(idList);

        List<BlackListVo> blackListVos = new ArrayList<>();
        BlackListVo blackListVo;

        for (UserInfo userInfo : userInfoList) {
            blackListVo = new BlackListVo();
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setNickname(userInfo.getNickName());
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());

            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    /**
     * 移除黑名单
     *
     * @param userId
     */
    @Override
    public void removeBlackList(Long userId) {
        User user = UserThreadLocal.get();
        this.blackListService.removeBlackList(user.getId(), userId);
    }

    /**
     * 通告设置
     *
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    @Override
    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        User user = UserThreadLocal.get();
        this.settingsService.updateNotification(user.getId(), likeNotification, pinglunNotification ,gonggaoNotification);
    }


}
